from flask import Flask, jsonify, request
from flask_cors import CORS
import logging
import time

app = Flask(__name__)
CORS(app)
logging.basicConfig(level=logging.INFO)

# 存储当前状态
current_state = {
    'emoji': '🤖',
    'message': '你好！我是你的智能家居助手 SAKI，让我们一起打造智慧家庭吧！'
}

# 添加监控消息存储
monitor_messages = []
MAX_MESSAGES = 50  # 最多保存50条消息

@app.route('/api/state', methods=['GET'])
def get_state():
    try:
        return jsonify(current_state)
    except Exception as e:
        logging.error(f"获取状态失败: {str(e)}")
        return jsonify({"error": "服务器内部错误"}), 500

@app.route('/api/update', methods=['POST'])
def update_state():
    try:
        data = request.json
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400

        if 'emoji' in data:
            current_state['emoji'] = data['emoji']
        if 'message' in data:
            current_state['message'] = data['message']

        logging.info(f"状态更新成功: {current_state}")
        return jsonify(current_state)
    except Exception as e:
        logging.error(f"更新状态失败: {str(e)}")
        return jsonify({"error": "服务器内部错误"}), 500

@app.route('/api/move', methods=['GET'])
def move_robot():
    try:
        x = float(request.args.get('x', 0))
        y = float(request.args.get('y', 0))
        # 这里添加实际的机器人控制代码
        logging.info(f"移动指令: x={x}, y={y}")
        return jsonify({"status": "success"})
    except Exception as e:
        logging.error(f"移动控制失败: {str(e)}")
        return jsonify({"error": "控制失败"}), 500

@app.route('/api/arm', methods=['GET'])
def control_arm():
    try:
        pose = request.args.get('pose', '')
        # 这里添加实际的机械臂控制代码
        logging.info(f"机械臂切换到: {pose}")
        return jsonify({"status": "success"})
    except Exception as e:
        logging.error(f"机械臂控制失败: {str(e)}")
        return jsonify({"error": "控制失败"}), 500

# 添加监控相关路由
@app.route('/api/monitor/messages', methods=['GET'])
def get_monitor_messages():
    return jsonify({'messages': monitor_messages})

@app.route('/api/monitor/send', methods=['POST', 'OPTIONS'])
def send_monitor_message():
    if request.method == 'OPTIONS':
        return '', 204
        
    try:
        data = request.json
        if 'message' in data:
            # 添加新消息到列表开头
            monitor_messages.insert(0, data['message'])
            # 保持消息数量限制
            while len(monitor_messages) > MAX_MESSAGES:
                monitor_messages.pop()
            logging.info(f"新增监控消息: {data['message']}")
            return jsonify({"status": "success"})
    except Exception as e:
        logging.error(f"处理监控消息失败: {str(e)}")
        return jsonify({"error": "发送失败"}), 500

@app.route('/api/control/<module>/<action>', methods=['POST'])
def handle_control(module, action):
    try:
        data = request.json
        # 模拟处理延迟
        time.sleep(0.5)
        logging.info(f"控制请求: 模块={module}, 动作={action}, 参数={data}")
        return jsonify({"status": "success"})
    except Exception as e:
        logging.error(f"控制失败: {str(e)}")
        return jsonify({"error": "控制失败"}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
